import { Component, OnInit, Injector } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { DetailBase } from 'app/modules/base/detail-base';
import { CertificationService, Assets } from '../../services/certification.service';
import { LoginService } from 'app/modules/login/services/login.service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'm-certification',
  templateUrl: './certification.component.html',
  styleUrls: ['./certification.component.scss']
})
export class CertificationComponent extends DetailBase implements OnInit {

  formGroup: FormGroup
  editing: boolean = false;
  fileToUpload;
  user$ = this.loginService.User$;
  constructor(
    private injector: Injector,
    private certificationService: CertificationService,
    private loginService: LoginService,
    public http: CertificationService
  ) {
    super(injector);

    this.formGroup = this.fb.group({
      assetsFile: this.fb.group({
        name: [''],
        content: [''],
        upload_at: [''],
      }),
    });

  }

  ngOnInit() {
    this.loadCertFile();
    this.formGroup.disable();
  }
  //取消按钮
  cancel() {
    this.loadCertFile();
    this.reload();
    this.editing = false;
    this.formGroup.setValue({
      assetsFile: {
        name: '',
        content: '',
        upload_at: '',
      },
    });
    this.formGroup.disable();
  }

  async submit() {
    if (this.fileToUpload) {
      let formData = new FormData();
      formData.append('file', this.fileToUpload);
      await this.certificationService.patchFile(formData);
      this.formGroup.setValue({
        assetsFile: {
          name: '',
          content: '',
          upload_at: '',
        },
      });
    } else {
        if(this.formGroup.value.assetsFile.name){
          this.cancel()
          return ;
        }
        await this.certificationService.deleteFile();
    }
    this.cancel();
    this.reload();
  }

  edit() {
    this.editing = true;
    this.formGroup.enable();
  }

  async onClickView(value) {
    window.open(`${value.content}`, '_blank');
  }

  onSelect(fileObj) {
    this.fileToUpload = fileObj.file;
  }
  //下载模板
async onDownTemp(value){
   const res = await this.http.getDownTemp();
    window.open(`${res['message']}`, '_blank');
  }

  async loadCertFile() {
    const resp: any = await this.certificationService.get();
    const assets: Assets = resp.message;
    if (assets) {
      let nameArr = assets.sys_value.split("/")
      let name = ""
      if (nameArr.length > 0){
        name = nameArr[nameArr.length-1]
      }
      //TODO
      this.formGroup.setValue({
        assetsFile: {
          name: name,
          content: assets.sys_value,
          // upload_at: new Date()
          upload_at: assets['updated_at']
        }
      })
    }
  }



}
